package com.dg.river.core.view;

import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @author jrj
 * @description: jrj 流式布局
 * @date :2022/7/23 21:53
 * @update jrj 2022/12/10 规范代码的方法名，变量名等
 */
public class FlowLayoutManager extends RecyclerView.LayoutManager {
    @Override
    public boolean isAutoMeasureEnabled() {
        return true;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        //这里是在布局前将所有在显示的HoldView从RecyclerView中剥离，将其放在缓存中，方便重新布局时使用。
        detachAndScrapAttachedViews(recycler);
        //curLineWidth 累加item布局时的x轴偏移
        int curLineWidth = 0;
        //curLineTop 累加item布局时的y轴偏移
        int curLineTop = 0;
        int lastLineMaxHeight = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View view = recycler.getViewForPosition(i);
            //获取每个item的布局参数，计算每个item的占用位置时需要加上margin
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
            addView(view);
            measureChildWithMargins(view, 0, 0);
            int width = getDecoratedMeasuredWidth(view) + params.leftMargin + params.rightMargin;
            int height = getDecoratedMeasuredHeight(view) + params.topMargin + params.bottomMargin;
            //累加当前行已有item的宽度
            curLineWidth += width;
            if (curLineWidth <= getWidth()) {
                //如果累加的宽度小于等于RecyclerView的宽度，不需要换行
                layoutDecorated(view, curLineWidth - width + params.leftMargin,
                        curLineTop + params.topMargin,
                        curLineWidth - params.rightMargin,
                        curLineTop + height - params.bottomMargin);
                //布局item的真实位置
                //比较当前行多有item的最大高度，用于换行后计算item在y轴上的偏移量
                lastLineMaxHeight = Math.max(lastLineMaxHeight, height);
            } else {
                //换行
                curLineWidth = width;
                if (lastLineMaxHeight == 0) {
                    lastLineMaxHeight = height;
                }
                //记录当前行top
                curLineTop += lastLineMaxHeight;
                layoutDecorated(
                        view,
                        params.leftMargin,
                        curLineTop + params.topMargin,
                        width - params.rightMargin,
                        curLineTop + height - params.bottomMargin
                );
                lastLineMaxHeight = height;
            }
        }
    }
}
